package com.tvserials.notification.parser;

import com.tvserials.notification.exceptions.NetworkConnectionException;
import com.tvserials.notification.utils.VOUtils;
import com.tvserials.notification.vo.TvEpisodeFilterVO;
import com.tvserials.notification.dto.EpisodeMedia;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by oleksandr.dokienko on 4/7/2014.
 */
public class LostFilmRssParser {
    public static String RSS_URL = "http://www.lostfilm.tv/rssdd.xml";
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss", Locale.ENGLISH);

    public List<EpisodeMedia> readRssFeed(TvEpisodeFilterVO filterVO) throws NetworkConnectionException {
        try {
            String content = new String(VOUtils.loadImage(RSS_URL), "windows-1251");
            Document document = Jsoup.parse(content, "http://www.lostfilm.tv", Parser.xmlParser());

            Elements items = document.select("channel").select("item");

            ArrayList<EpisodeMedia> episodeMedias = new ArrayList<EpisodeMedia>();
            for (Element element : items) {
                String title = element.getElementsByTag("title").text();
                String description = element.getElementsByTag("description").text();
                String link = element.getElementsByTag("link").text();
                String dateStr = element.getElementsByTag("pubDate").text();

                EpisodeMedia episodeMedia = new EpisodeMedia();
                episodeMedia.setTitle(title);
                episodeMedia.setDescription(description);
                episodeMedia.setLink(link);
                episodeMedia.setPubDate(getDate(dateStr));
                episodeMedias.add(episodeMedia);
            }
            return episodeMedias;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Date getDate(String dateStr) {
        try {
            return simpleDateFormat.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

}
